package bfs;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * @author wcj
 * @Date 2021/7/6 21:19
 * @Version 1.0
 */
public class LevelOrder {

    /**
     * 层序遍历，从左到右，从下到上输出
     *
     * @param root
     * @return
     */
    public static List<List<Integer>> bfs(TreeNode root) {
        LinkedList<List<Integer>> res = new LinkedList<>();
        Queue<TreeNode> queue = new LinkedList<>();
        if (root != null) {
            queue.add(root);
        }
        while (!queue.isEmpty()) {
            List<Integer> t = new ArrayList<>();
            for (int i = queue.size() - 1; i >= 0; i--) {
                TreeNode tmp = queue.poll();
                if (tmp.left != null) {
                    queue.add(tmp.left);
                }
                if (tmp.right != null) {
                    queue.add(tmp.right);
                }
                t.add(tmp.val);
            }
            res.addFirst(t);
        }
        return res;
    }
}
